package com.ls.lserp.modules.purchase.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.material.entity.MaterialStock;
import com.ls.lserp.modules.material.service.MaterialStockService;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.purchase.entity.PuttingContract;
import com.ls.lserp.modules.purchase.service.PurchaseContractService;
import com.ls.lserp.modules.purchase.service.PuttingContractService;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.service.SupplierService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/putting/contract/")
public class PuttingContractController extends BaseController {

	//客户类别
			//甲方
			public static final Long OGNIZATION_TYPE_A= 9L;
			//乙方
			public static final Long OGNIZATION_TYPE_B= 3L;
	@Autowired
	private PuttingContractService puttingContractService;
	@Autowired
	private PurchaseContractService purchaseContractService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	Configuration freemarkerConfiguration;
	@ModelAttribute
	public PuttingContract get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return puttingContractService.findByID(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new PuttingContract();
		}
	}
	
	
	/**
	 * 原辅料库存一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String puttingContract() {

		return "modules/purchase/puttingContract";

	}
	
	/**
	 * 拼接一览画面
	 * @param values 
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("purchase:contract:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model, String[] values) throws Exception {
			Map<Object, Object> listMap = new HashMap<Object, Object>();
			// ajax回调时使用的一览list名
			request.setAttribute("listNames", "puttingContract");
			// 画面取得的检索项目
			String contractProcessNO = puttingContract.getContractProcessNO();
			String ognizationNameB = puttingContract.getOgnizationNameB();
			String dateStart = puttingContract.getDateStart();
			String dateEnd = puttingContract.getDateEnd();
			String ulSelected = puttingContract.getUlSelected();
			puttingContract.setDeleteFlag("0");
			if ("2".equals(ulSelected)) {
				ulSelected = "AUDIT_STATUS-AUDIT_10";
				puttingContract.setUlSelected(ulSelected);
				
			}else if ("1".equals(ulSelected)) {
				ulSelected = "AUDIT_STATUS-AUDIT_20";
				puttingContract.setUlSelected(ulSelected);
				
			}else if ("0".equals(ulSelected)) {
				ulSelected = "AUDIT_STATUS-AUDIT_30";
				puttingContract.setUlSelected(ulSelected);
				
			}else if ("5".equals(ulSelected)) {
				ulSelected = "AUDIT_STATUS-AUDIT_00";
				puttingContract.setUlSelected(ulSelected);
				
			}else if ("4".equals(ulSelected)) {
				ulSelected = "-1";
				puttingContract.setUlSelected(ulSelected);
				puttingContract.setDeleteFlag("1");
				
			}
			// 拼接字符串供分页使用
			String searchParam = "&contractProcessNO=" + contractProcessNO+"&ognizationNameB=" + ognizationNameB+"&dateStart="+ dateStart+"&dateEnd="+ dateEnd+"&ulSelected="+ ulSelected;
			//放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
			request.setAttribute(Global.SEARCH_PAEAM, searchParam);
			// 查询一览页面数据
			Page<PuttingContract> page = puttingContractService.findPuttingContractList(new Page<PuttingContract>(request, response),
					puttingContract);
			// 读取文件生成字符串
			String strUri = request.getContextPath() + Global.getAdminPath();
			String strHtml = "";
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("contractList", page.getList());
			map.put("pageNo", page.getPageNo());
			map.put("pageSize", page.getPageSize());
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("puttingContractList.ftl"), map);
			listMap.put("puttingContract", strHtml);
			listMap.put("page", page.getHtml());
			// ajax返回结果
			return renderString(response, listMap);
		}
	
	/**
	 * 拼接供货商一览画面
	 * @param ognization
	 * 
	 * 
	 * @return 
	 */
	@RequiresPermissions("purchase:contract:view")
	@RequestMapping(value = { "searchSupplierList" })
	@ResponseBody
	public String searchSupplierList(Ognization ognization, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute("listNames", "supplier");
		// 画面取得的检索项目
		String pSupplierName = ognization.getOgnizationName();
		String pCateCd = ognization.getOgnizationCategoryCd();
		// 拼接字符串供分页使用
		String searchParam = "&ognizationName=" + pSupplierName + "&ognizationCategoryCd=" + pCateCd;
		//放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		ognization.setOgnizationType(OGNIZATION_TYPE_B);
		ognization.setCurrentUser(ognization.getCurrentUser());
		// 查询一览页面数据
		Page<Ognization> page = supplierService.findList(new Page<Ognization>(request, response), ognization);
		// 读取文件生成字符串
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("supplierList", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("supplierList.ftl"), map);
		listMap.put("supplier", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}
	
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	/**
	 * 创建外发合同信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("putting:contract:view")
	@RequestMapping(value = {"createContract"})
	public String createContract(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model){
		Ognization ognization = new Ognization();
		ognization.setOgnizationType(OGNIZATION_TYPE_A);
		ognization = purchaseContractService.getPartyA(ognization);
		ognization.preInsert();
		model.addAttribute("ognization",ognization);
		return "modules/purchase/puttingContractCreate";
	}
	/**
	 * 查看一条外发合同信息
	 * 
	 * @return
	 */
	@RequiresPermissions("putting:contract:view")
	@RequestMapping(value = {"viewContract"})
	public String viewContract(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model){
		List<PuttingContract> styleList = puttingContractService.findStyleByID(puttingContract);
		puttingContract = puttingContractService.getContract(puttingContract);
		puttingContract.setStyleList(styleList);
		model.addAttribute("puttingContract",puttingContract);
		return "modules/purchase/puttingContractShow";
	}
	/**
	 * 编辑外发合同信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("putting:contract:view")
	@RequestMapping(value = {"editContract"})
	public String editContract(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model){
		List<PuttingContract> styleList = puttingContractService.findStyleByID(puttingContract);
		puttingContract = puttingContractService.getContract(puttingContract);
		puttingContract.setStyleList(styleList);
		model.addAttribute("puttingContract",puttingContract);
		return "modules/purchase/puttingContractCreate";
	}
	/**
	 * 乙方客户一览画面
	 * 
	 * @return
	 */
	@RequiresPermissions("putting:contract:view")
	@RequestMapping(value = {"supplierList"})
	public String supplierList(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model){
		
		model.addAttribute("puttingContract",puttingContract);
		return "modules/purchase/purchaseContractCreate2";
	}
	/**
	 * 创建编辑保存仓库信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("putting:contract:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(puttingContract.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			PuttingContract puttingContractNew = get(puttingContract.getId().toString());
			// 判断数据是否删除
            if(puttingContractNew==null || BaseEntity.DEL_FLAG_DELETE.equals(puttingContractNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
            }
			
            // 排他处理
		    if(puttingContract.getVersion()==get(puttingContract.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	puttingContract.setVersion(puttingContract.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		    }
		}
			
			
		    // 保存数据
		puttingContractService.savePuttingContract(puttingContract);
			
			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));
			
			
	}
	/**
	 * 提交采购预付款信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("putting:contract:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(puttingContract.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			PuttingContract puttingContractNew = get(puttingContract.getId().toString());
			// 判断数据是否删除
            if(puttingContractNew==null || BaseEntity.DEL_FLAG_DELETE.equals(puttingContractNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
            }
			
            // 排他处理
		    if(puttingContract.getVersion()==get(puttingContract.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	puttingContract.setVersion(puttingContract.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		    }
		}
		
			
			
		    // 保存数据
		puttingContractService.deletePuttingContract(puttingContract);
			
			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));
			
			
	}
	/**
	 * 提交采购预付款信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("putting:contract:edit")
	@RequestMapping(value = "commit")
	@ResponseBody
	public String commit(PuttingContract puttingContract, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(puttingContract.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			PuttingContract puttingContractNew = get(puttingContract.getId().toString());
			// 判断数据是否删除
            if(puttingContractNew==null || BaseEntity.DEL_FLAG_DELETE.equals(puttingContractNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
            }
			
            // 排他处理
		    if(puttingContract.getVersion()==get(puttingContract.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	puttingContract.setVersion(puttingContract.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		    }
		}
		
	    // 保存数据
		puttingContractService.commitPuttingContract(puttingContract);
		
		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));
		
		
}
	/**
	 * 审核页面
	 * @param puttingContract
	 * @param model
	 * @return
	 */
	@RequiresPermissions("putting:contract:audit")
	@RequestMapping(value = "audit")
	public String audit(PuttingContract puttingContract,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		// 履历一览取得
		AuditInfo auditInfo = new AuditInfo();
		// id
		auditInfo.setAuditRelateId(puttingContract.getId());
		// 阶段
		auditInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_putting"));
		AuditInfo resultInfo = puttingContractService.findAuditInfo(auditInfo);
		
	
				resultInfo.setAuditRelateId(puttingContract.getId());
				
				resultInfo.setAuditRelateNo(puttingContract.getContractProcessNO());
				
				resultInfo.setAuditPhaseCd(ResourcesUtil.getConfig("audit_phase_putting"));
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("auditInfo", resultInfo);
		
		// 返回页面地址
		return "modules/order/auditInfo";
	}
	
	/**
	 * 保存履历信息
	 * @param auditInfo
	 * @param request
	 * @param model
	 * @param response
	 * @return
	 * @throws ResourceException 
	 */
	@RequiresPermissions("putting:contract:edit")
	@RequestMapping(value = "saveAudit")
	@ResponseBody
	public String saveAudit(AuditInfo auditInfo,HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
		
		// 是否需要更新样品需求状态
		boolean isUpdateStatus = false;
		
		// 判断数据是否删除
		PuttingContract puttingContract=get(Long.toString(auditInfo.getAuditRelateId()));
		// 判断数据是否删除
		if(puttingContract.getContractProcessNO()==null || BaseEntity.DEL_FLAG_DELETE.equals(puttingContract.getDeleteFlag())){
			// 返回提示信息
			return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}
		
        // 审核结果已经通过,返回错误提示信息
		AuditInfo pAuditResult = new AuditInfo();
		pAuditResult.setAuditPhaseCd(auditInfo.getAuditPhaseCd());
		pAuditResult.setAuditRelateId(auditInfo.getAuditRelateId());
		if(puttingContractService.getAuditResult(pAuditResult)>0){
	    	// 返回提示信息
	        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		}
	    // 保存样品数据
		//外发合同
		puttingContractService.saveAuditInfo(auditInfo,isUpdateStatus);
		// 保存成功返回提示信息
	    return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "audit_ok_msg")));
	
	}
	
	@RequiresPermissions("putting:contract:edit")
	@ResponseBody
	@RequestMapping(value = "exportFile")
	public String exportFile(PuttingContract puttingContract ,HttpServletResponse response){
		try {
            // 模版
            String basePath = SystemPath.getClassPath();
            String tempFilePath = "/" + basePath + "puttingContract.xlsx";
            ExcelTemplate handle = this.puttingContractService.export(puttingContract, tempFilePath);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" +  puttingContract.getContractProcessNO()  +".xlsx");
            OutputStream os = response.getOutputStream();
            // 写到输出流并关闭资源
            handle.writeAndClose(tempFilePath, os);
            os.flush();
            os.close();
            handle.readClose(tempFilePath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
}
